package org.itboys.mobile.service.mongo.mobile;

import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.framework.resource.ResourceHolder;
import org.itboys.kitchen.util.MobileSignUtils;
import org.itboys.mobile.common.SundayCommonConstants;

import org.itboys.mobile.dto.count.KitchenCountDto;
import org.itboys.mobile.dto.count.KitchenCountProductDto;
import org.itboys.mobile.dto.product.SundayProductDto;
import org.itboys.mobile.entity.mongo.KitchenCart;
import org.itboys.mobile.entity.mongo.SundayMember;
import org.itboys.mobile.entity.mysql.product.SundayProduct;
import org.itboys.mobile.service.mongo.web.SundayMemberService;
import org.itboys.mobile.service.mysql.mobile.product.SundayMobileProductService;
import org.itboys.mongodb.core.MongoDataSource;
import org.itboys.mongodb.service.BaseMongoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_购物车_service_移动端
 */
@Service
public class KitchenMobileCartService extends BaseMongoService<KitchenCart>{
    @Autowired
    private SundayMobileProductService productService;
    @Autowired
    private SundayMemberService memberService;


    @Resource(name = "mobileDs")
    private MongoDataSource kitchenDataSource;
    @Override
    protected MongoDataSource getMongoDataSource() {
        return kitchenDataSource;
    }

    @Override
    protected Class<KitchenCart> getEntityClass() {
        return KitchenCart.class;
    }


    /**
     * 新增购物车（支持批量新增）。
     * @param memberId
     * @param productIds
     * @param nums
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @param villageId
     * @return
     */
    public  List<Long> addCart(Long memberId,List<Long> productIds ,List<Integer> nums,Integer cartType,Long villageId){



        if(ListUtil.isNull(productIds)||ListUtil.isNull(nums)||(productIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        //如果是立即购买加入购物车，先删除原来购物车中立即购买加入的数据
        if(cartType==SundayCommonConstants.cart_type_buy_now){
            deleteCart(null,memberId,SundayCommonConstants.cart_type_buy_now);
        }
            //返回结果
        List<Long> cartIds = new ArrayList<Long>();
        //获取要加入的商品
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);
        //旧购物车数据
         param.clear();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        param.put("cartType",cartType);
        if(LongUtil.isNotZreo(villageId)){
            param.put("villageId",villageId);
        }
        List<KitchenCart> oldCarts=super.list(param);
        List<KitchenCart> needToAdd=new ArrayList<KitchenCart>();

        //比对出哪一些商品是需要新增的，哪一些是增加数量的
        for(int i=0;i< products.size();i++){
            SundayProduct product = products.get(i);
            Integer num =nums.get(i);
            boolean isExist=false;
            for(KitchenCart oldCart:oldCarts){
                if(oldCart.getProductId().longValue()==product.getId().longValue()){
                    isExist=true;
                    super.update(oldCart.getId(),"num",num+oldCart.getNum());
                    break;
                }
            }
            //本次需要新增的商品
            if(!isExist){
                needToAdd.add(new KitchenCart(memberId, product.getId(), num,cartType, villageId));
            }
        }
        if(ListUtil.isNotNull(needToAdd)){
            super.batchSave(needToAdd);
        }
        for(KitchenCart needToAd:needToAdd){
            cartIds.add(needToAd.getId());
        }
        return cartIds;

    }

    /**
     * 修改购物车数量，支持批量修改
     * @param memberId
     * @param cartIds
     * @param nums
     */
    public void updateCart(Long memberId ,List<Long> cartIds ,List<Integer> nums){
        if(ListUtil.isNull(cartIds)||ListUtil.isNull(nums)||(cartIds.size()!=nums.size())){
            throw new ErrorException("传入参数错误");
        }
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("id in",cartIds);
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        List<KitchenCart> carts = super.list(param);
        for(int i=0;i<carts.size();i++){
            KitchenCart cart = carts.get(i);
            Integer num = nums.get(i);
            //数量变更后才操作数据库。执行修改
            if(cart.getNum()!=num){
                super.update(cart.getId(),"num",num);
            }
        }
    }


    /**
     * 删除购物车，支持批量删除
     * @param cartIds
     * @param memberId
     * @param cartType
     */
    public void deleteCart(List<Long> cartIds ,Long memberId,Integer cartType){
        Map<String,Object> param = new HashMap<String,Object>();
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(cartType!=null){
            param.put("cartType",cartType);
        }

        super.delete(param);
    }


    /**
     * 获取购物车。不分页。返回上
     * @param memberId
     * @param cartIds 结算/生成订单时传入此参数/手机端合计购物车商品价格（如系统含有满减，x元任选等促销手段）
     * @param cartType 1,通过购物车加入的；2，通过立即购买加入的
     * @param villageId
     * @return
     */
    public KitchenCountDto getCart(Long memberId,  List<Long> cartIds,Integer cartType,Long villageId){
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("memberId",memberId);
        param.put("isDeleted",0);
        if(LongUtil.isNotZreo(villageId)){
            param.put("villageId",villageId);
        }
        if(ListUtil.isNotNull(cartIds)){
            param.put("id in",cartIds);
        }
        if(cartType!=null){
            param.put("cartType",cartType);
        }


        List<KitchenCart> carts = super.list(param);
        //购物车外层数据。总价
        KitchenCountDto countDto = new KitchenCountDto();
        countDto.setTotalAmount(new BigDecimal("0"));
        countDto.setPayAmount(new BigDecimal("0"));
        countDto.setMemberId(memberId);
        if(ListUtil.isNull(carts))return countDto;
        //对应的商品数据
        List<Long> productIds = new ArrayList<Long>();
        for(KitchenCart cart:carts){
            productIds.add(cart.getProductId());
        }
        param.clear();
        param.put("ids",productIds);
        List<SundayProduct> products = productService.select(param);

        //获取当前购物车的类型。1，商城，2积分，3采购
        Integer type= null;
        SundayMember member=memberService.getById(memberId);
        //用户对应商城类型
        if(member.getUserType()==SundayCommonConstants.user_type_member){
            type=SundayCommonConstants.type_mall;
            //用户可以兑换积分商品。对应积分类型
            if(products.get(0).getType()==SundayCommonConstants.type_score){
                type=SundayCommonConstants.type_score;
            }
            //门店或大客户对应采购类型
        }else if(member.getUserType()==SundayCommonConstants.user_type_shop||
                member.getUserType()==SundayCommonConstants.user_type_customer){
            type=SundayCommonConstants.type_caigou;
        }
       products=productService.getShopProduct(null,
                null,
                type,
                null,
                memberId,
                productIds,
                villageId,true);
        List<SundayProductDto> productDtos=productService.packageDtoMuilt(products);
        //根据用户类型获取商品真实价格
        //products=productService.getRealPrice2(products,memberId,null,villageId);

        //购物车商品
        List<KitchenCountProductDto> countProducts = new ArrayList<KitchenCountProductDto>();
        Double totalAmount = 0.00;
        Double payAmount=0.00;

        //零售价
      /*  Double retailAmount=0.00;*/
      //成本价
        Double costAmount=0.00;
       /* for(KitchenCart cart:carts){
            for(SundayProduct product:products){
                if(cart.getProductId().longValue()==product.getId().longValue()){
                    KitchenCountProductDto countProduct = new
                            KitchenCountProductDto(product.getId(), product.getCreateTime(), product.getCreateDate(),
                            cart.getId(), product.getPrice(), product.getName(),product.getNumber(), product.getImage(), product.getStandard(),cart.getNum(),
                            product.getType(),0, product.getCostPrice(),product.getStore(),product.getItemCode());
                    totalAmount+=product.getPrice().doubleValue()*cart.getNum();
                    payAmount+=product.getPrice().doubleValue()*cart.getNum();
                    costAmount+=product.getCostPrice().doubleValue()*cart.getNum();
                    countProducts.add(countProduct);
                    //设置购物车/结算商品类型。便于前端显示钱还是积分
                    product.setType(type);
                    break;
                }
            }

        }*/
        for(KitchenCart cart:carts){
            for(SundayProductDto product:productDtos){
                if(cart.getProductId().longValue()==product.getId()){
                    KitchenCountProductDto countProduct = new
                            KitchenCountProductDto(product.getId(), product.getCreateTime(), product.getCreateDate(),
                            cart.getId(), product.getPrice(), product.getName(),product.getNumber(), product.getImage(), product.getStandard(),cart.getNum(),
                            product.getType(),0, product.getCostPrice(),product.getStore(),product.getItemCode());
                    totalAmount+=product.getPrice().doubleValue()*cart.getNum();
                    payAmount+=product.getPrice().doubleValue()*cart.getNum();
                    if(product.getCostPrice()!=null){
                        costAmount+=product.getCostPrice().doubleValue()*cart.getNum();
                    }

                    countProducts.add(countProduct);
                    //设置购物车/结算商品类型。便于前端显示钱还是积分
                    product.setType(type);
                    break;
                }
            }

        }
        countDto.setTotalAmount(new BigDecimal(totalAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        countDto.setPayAmount(new BigDecimal(payAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        countDto.setCostAmount(new BigDecimal(costAmount).setScale(2,BigDecimal.ROUND_HALF_UP));
        countDto.setType(type);
        countDto.setProducts(countProducts);

        return countDto;
    }




}
